// Copyright 2009 StarCite Inc.  All rights reserved.
// FileUtil.java 1:50:08 PM danny.liu
package com.billowsoft.syncer.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author danny.liu Nov 30, 2011
 * @version 1.0
 * 
 */
public final class FileUtil {

	public static void copy(String sourceDir, String sourceFileName,
			String destDir) {

		File sourceFile = new File(getFullPath(sourceDir, sourceFileName));
		if (sourceFile.isDirectory()) {
			String newDestDirPath = getFullPath(destDir, sourceFileName);
			File newDestDir = new File(newDestDirPath);
			if (!newDestDir.exists() && !newDestDir.mkdir()) {
				throw new RuntimeException("Create directory " + newDestDir
						+ " failed.");
			}
			for (File file : sourceFile.listFiles()) {
				copy(getFullPath(sourceDir, sourceFileName), file.getName(), newDestDirPath);
			}
		} else {
			copyFile(sourceFile, destDir);
		}
	}

	public static void copyFile(File sourceFile, String destDir) {

		FileInputStream inputStream = null;
		FileOutputStream outputStream = null;
		String sourceFileName = sourceFile.getName();
		try {
			inputStream = new FileInputStream(sourceFile);
			String destFileName = getFullPath(destDir, sourceFileName);
			File destFile = new File(destFileName);
			if(destFile.exists()){
				if(!destFile.delete()){
					throw new RuntimeException("Delete server file " + destFileName + " failed.");
				}
			}
			outputStream = new FileOutputStream(destFile);
			byte[] content = new byte[2048];
			int length = inputStream.read(content);
			while (length != -1) {
				outputStream.write(content, 0, length);
				length = inputStream.read(content);
			}
		} catch (FileNotFoundException e) {
			throw new RuntimeException(String.format(
					"Copy file from %s to directory %s failed.",
					sourceFileName, destDir), e);
		} catch (IOException e) {
			throw new RuntimeException(String.format(
					"Copy file from %s to directory %s failed.",
					sourceFileName, destDir), e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	private static String getFullPath(String sourceDir, String sourceFileName) {
		return sourceDir + File.separator + sourceFileName;
	}

}
